<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="80px" @keyup.enter.native="dataFormSubmit()">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.Type">
          <el-radio v-for="(type, index) in dataForm.TypeList" :key="index" :label="index">{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="dataForm.TypeList[dataForm.Type] + '名称'" prop="Name">
        <el-input v-model="dataForm.Name" :placeholder="dataForm.TypeList[dataForm.Type] + '名称'" />
      </el-form-item>
      <el-form-item label="上级菜单" prop="ParentName">
        <el-popover
          ref="menuListPopover"
          v-model="parentVisible"
          :width="parentWidth"
          placement="bottom-start"
          trigger="click"
          @show="getPopover('parentName','menuListPopover')"
        >
          <div style="height: 200px;overflow-y:auto">
            <el-tree
              ref="menuListTree"
              :data="menuList"
              :props="menuListTreeProps"
              node-key="Id"
              :default-expand-all="false"
              :highlight-current="true"
              :expand-on-click-node="false"
              @current-change="menuListTreeCurrentChangeHandle"
            />
          </div>
        </el-popover>
        <el-input ref="parentName" v-model="dataForm.ParentName" v-popover:menuListPopover :readonly="true" placeholder="点击选择上级菜单" class="menu-list__input" />
      </el-form-item>
      <el-form-item v-if="dataForm.Type === 1" label="菜单路由" prop="Url">
        <el-input v-model="dataForm.Url" placeholder="菜单路由" />
      </el-form-item>
      <el-form-item v-if="dataForm.Type !== 0" label="授权标识" prop="perms">
        <el-input v-model="dataForm.Perms" placeholder="多个用逗号分隔, 如: user:list,user:create" />
      </el-form-item>
      <el-form-item v-if="dataForm.Type !== 2" label="排序号" prop="orderNum">
        <el-input-number v-model="dataForm.OrderNum" controls-position="right" :min="0" label="排序号" />
      </el-form-item>
      <el-form-item v-if="dataForm.Type !== 2" label="菜单图标" prop="Icon">
        <el-row>
          <el-col :span="22">
            <el-popover
              ref="iconListPopover"
              placement="bottom-start"
              trigger="click"
              popper-class="mod-menu__icon-popover"
            >
              <div class="mod-menu__icon-inner">
                <div class="mod-menu__icon-list">
                  <el-button
                    v-for="(item, index) in iconList"
                    :key="index"
                    :class="{ 'is-active': item === dataForm.Icon }"
                    @click="iconActiveHandle(item)"
                  >
                    <svg-icon :icon-class="item" class-name="custom-class" />
                  </el-button>
                </div>
              </div>
            </el-popover>
            <el-input v-model="dataForm.Icon" v-popover:iconListPopover :readonly="true" placeholder="菜单图标名称" class="icon-list__input" />
          </el-col>
          <el-col :span="2" class="icon-list__tips">
            <el-tooltip placement="top" effect="light">
              <div slot="content">全站推荐使用SVG Sprite, 详细请参考:<a href="//github.com/daxiongYang/renren-fast-vue/blob/master/src/icons/index.js" target="_blank">icons/index.js</a>描述</div>
              <i class="el-icon-warning" />
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <el-row :gutter="40">
      <el-col :span="24" style="text-align: right;">
        <el-button size="small" @click="visible = false">
          <span class="font-12 iconfont myicon-quxiao1" />&nbsp;取消
        </el-button>
        <el-button size="small" type="primary" @click="dataFormSubmit()">
          <span class="font-12 iconfont myicon-tongguo" />&nbsp;确定
        </el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from '@/utils'
import { fetchMenu, saveMenu, getMenu, updateMenu } from '@/api/menu'
import Icon from '@/icons'
export default {
  data() {
    var validateUrl = (rule, value, callback) => {
      if (this.dataForm.Type === 1 && !/\S/.test(value)) {
        callback(new Error('菜单URL不能为空'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      parentVisible: false,
      parentWidth: 0,
      dataForm: {
        Id: 0,
        Type: 1,
        TypeList: ['目录', '菜单', '按钮'],
        Name: '',
        ParentId: 0,
        ParentName: '',
        Url: '',
        Perms: '',
        OrderNum: 0,
        Icon: '',
        iconList: []
      },
      dataRule: {
        Name: [
          { required: true, message: '菜单名称不能为空!', trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: '上级菜单不能为空', trigger: 'change' }
        ],
        Url: [
          { validator: validateUrl, trigger: 'blur' }
        ]
      },
      menuList: [],
      menuListTreeProps: {
        label: 'Name',
        children: 'children'
      }
    }
  },
  created() {
    this.iconList = Icon.getNameList()
  },
  methods: {
    getPopover(container, popover) {
      this.parentWidth = this.$refs[container].$el.offsetWidth
      this.parentVisible = true
    },
    init(id) {
      this.dataForm.id = id || 0
      fetchMenu().then(({ data }) => {
        this.menuList = treeDataTranslate(data, 'Id')
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.dataForm.Icon = ''
        })
      }).then(() => {
        if (id && id > 0) {
          getMenu(id).then((data) => {
            if (data && data.code === '20000') {
              this.dataForm.Id = data.menu.Id
              this.dataForm.Type = data.menu.Type
              this.dataForm.Name = data.menu.Name
              this.dataForm.ParentId = data.menu.ParentId
              this.dataForm.Url = data.menu.Url
              this.dataForm.Perms = data.menu.Perms
              this.dataForm.OrderNum = data.menu.OrderNum
              this.dataForm.Icon = data.menu.Icon
              this.menuListTreeSetCurrentNode()
            }
          })
        }
      })
    },
    // 菜单树选中
    menuListTreeCurrentChangeHandle(data, node) {
      this.dataForm.ParentId = data.Id
      this.dataForm.ParentName = data.Name
      this.parentVisible = false
    },
    // 菜单树设置当前选中节点
    menuListTreeSetCurrentNode() {
      this.$refs.menuListTree.setCurrentKey(this.dataForm.ParentId)
      this.dataForm.ParentName = (this.$refs.menuListTree.getCurrentNode() || {})['Name']
    },
    // 图标选中
    iconActiveHandle(iconName) {
      this.dataForm.Icon = iconName
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var data = {
            'Id': this.dataForm.Id || undefined,
            'Type': this.dataForm.Type,
            'Name': this.dataForm.Name,
            'ParentId': this.dataForm.ParentId,
            'Url': this.dataForm.Url,
            'Perms': this.dataForm.Perms,
            'OrderNum': this.dataForm.OrderNum,
            'Icon': this.dataForm.Icon
          }
          var permission
          if (this.dataForm.Id && this.dataForm.Id > 0) {
            permission = updateMenu(data)
          } else {
            permission = saveMenu(data)
          }
          permission.then((data) => {
            if (data && data.code === '20000') {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.mod-menu {
  .menu-list__input,
  .icon-list__input {
     > .el-input__inner {
      cursor: pointer;
    }
  }
  &__icon-popover {
    width: 458px;
    overflow: hidden;
  }
  &__icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  &__icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
  .icon-list__tips {
    font-size: 18px;
    text-align: center;
    color: #e6a23c;
    cursor: pointer;
  }
}
</style>
